﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Data;

namespace Net_SCADA
{
    class fdPublicFunction
    {
        [StructLayout(LayoutKind.Sequential)]
        struct LASTINPUTINFO
        {
            [MarshalAs(UnmanagedType.U4)]
            public int cbSize;
            [MarshalAs(UnmanagedType.U4)]
            public uint dwTime;
        }
        [DllImport("user32.dll")]
        static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);

        [DllImport("user32.dll")]
        private static extern bool
        SetForegroundWindow(IntPtr hWnd);
        [DllImport("user32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd , int nCmdShow);
        [DllImport("user32.dll")]
        private static extern bool IsIconic(IntPtr hWnd);
        // 消息函数
        [DllImport("user32.dll" , EntryPoint = "PostMessageA")]
        public static extern bool PostMessage(IntPtr hWnd , int Msg , int wParam , int lParam);
        [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(string strclassName , string strWindowName);
        [DllImportAttribute("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd , int Msg , int wParam , int lParam);
        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_MAXIMIZE = 0xF030;


        public static BoxColor[] boxColorSet { get; set; } = new BoxColor[6] {
            new BoxColor(){ colorName="绿色;Green".Split(';'),foreColor=Color.FromName("Black"),backColor=Color.Lime},
            new BoxColor(){ colorName="紫色;Purple".Split(';'),foreColor=Color.Black,backColor=Color.Violet},
            new BoxColor(){ colorName="蓝色;Blue".Split(';'),foreColor=Color.White,backColor=Color.Blue},
            new BoxColor(){ colorName="青色;Cyan".Split(';'),foreColor=Color.Black,backColor=Color.Aqua},
            new BoxColor(){ colorName="橙色;Orange".Split(';'),foreColor=Color.Black,backColor=Color.Orange},
            new BoxColor(){ colorName="黄色;Yellow".Split(';'),foreColor=Color.Black,backColor=Color.Yellow},
        };

        public static void LoadBoxColorset()
        {
            DataTable dt = DBOperate.getBoxColorSet();
            if (dt == null || dt.Rows.Count == 0) return;
            boxColorSet=new BoxColor[dt.Rows.Count];    
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                boxColorSet[i] = new BoxColor() {
                    colorName = dt.Rows[i]["name"].ToString().Split(';'),
                    foreColor =Color.FromName( dt.Rows[i]["foreColorName"].ToString()),
                    backColor = Color.FromName( dt.Rows[i]["backColorName"].ToString()),
                };
            }
        }


        /// <summary>
        /// 获取无操作的时间
        /// </summary>
        /// <returns>返回的时无操作时间，毫秒</returns>
        public static long GetLastInputTime()
        {
            LASTINPUTINFO vLastInputInfo = new LASTINPUTINFO();
            vLastInputInfo.cbSize = Marshal.SizeOf(vLastInputInfo);
            if (!GetLastInputInfo(ref vLastInputInfo)) return 0;
            return Environment.TickCount - (long)vLastInputInfo.dwTime;
        }

        public static bool isStart = true;
        private static string _queryFile= Application.StartupPath + "\\WZXC_GBL_QUERY.exe";
        private static string _queryFilename ="WZXC_GBL_QUERY";
        private static Process pro;
        /// <summary>
        /// 启动历史查询软件，注意的是，当软件已经被关闭的时候会有异常，这个时候就在异常的过程中启动查询软件
        /// </summary>
        public static void Query()
        {
            Process[] processes = Process.GetProcessesByName(_queryFilename);
            if (processes.Length > 0)
            {
                IntPtr hWnd = processes[0].MainWindowHandle;
                if (IsIconic(hWnd))
                    ShowWindowAsync(hWnd , 9);// 9就是SW_RESTORE标志，表示还原窗体
                                              //SendMessage(hWnd, WM_SYSCOMMAND, SC_MAXIMIZE, 0);
                SetForegroundWindow(hWnd);
            }
            else
               if (File.Exists(_queryFile)) Process.Start(_queryFile);
        }


        public static bool CheckInput(int dp , string content , KeyPressEventArgs e)
        {
            bool result = false;
            if (dp > 0)
            {
                if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar != 46)
                    result = true;
                //小数点的处理。
                if ((int)e.KeyChar == 46)                           //小数点
                {
                    if (content.Length <= 0)
                        result = true;   //小数点不能在第一位
                    else
                    {
                        float f;
                        float oldf;
                        bool b1 = false, b2 = false;
                        b1 = float.TryParse(content , out oldf);
                        b2 = float.TryParse(content + e.KeyChar.ToString() , out f);
                        if (b2 == false)
                        {
                            if (b1 == true)
                                result = true;
                            else
                                result = false;
                        }
                    }
                }
            }
            else
            {
                if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8)
                    result = true;
            }
            return result;
        }

        /// <summary>
        /// 保存当前的数据到文件中
        /// </summary>

        public static void Delay(int mSecond)
        {
            int start = Environment.TickCount;
            while (Math.Abs(Environment.TickCount - start) < mSecond)
            {
                Thread.Sleep(5);
                Application.DoEvents();
            }

        }
        /// <summary>
        /// 获得一个控件上需要显示字体的最大值
        /// </summary>
        /// <param name="height">允许字体的最大高度</param>
        /// <param name="fonttype">字体/param>
        /// <param name="fontStyle">显示方式</param>
        /// <returns></returns>
        public static Font Getfont(int height, string fonttype, FontStyle fontStyle)
        {
            Label alabel = new Label();
            SizeF sizeF;
            string str = "1234";
            float fontsize = 5f;
            Font font;
            Graphics g = alabel.CreateGraphics();
            g.PageUnit = GraphicsUnit.Pixel;
            while (true)
            {
                font = new Font(fonttype, fontsize, fontStyle);// new Font("Arial", fontsize, FontStyle.Bold);
                sizeF = g.MeasureString(str, font);
                if (sizeF.Height >= height)
                {
                    return font;
                }
                fontsize += 0.5f;
            }
        }

        public static SizeF GetTextSize(Font font , string content)
        {
            SizeF sizeF;
            Label alabel = new Label();
            alabel.Font = font; 
            alabel.Text = content;
            Graphics g = alabel.CreateGraphics();
            sizeF = g.MeasureString(alabel.Text , font);
            return sizeF;
        }

        /// <summary>
        /// 获得对应文字的高度
        /// </summary>
        /// <param name="font">需要传入对应的字体</param>
        /// <returns></returns>
        public static float GetTextHeight(Font font)
        {
            SizeF sizeF;
            Label alabel = new Label();
            alabel.Text = "测试字符";
            Graphics g = alabel.CreateGraphics();
            sizeF = g.MeasureString(alabel.Text, font);
            return sizeF.Height;
        }

        /// <summary>
        /// 获取文件文本的编码
        /// </summary>
        /// <param name="FILE_NAME"></param>
        /// <returns></returns>
        public static System.Text.Encoding GetFileType(string FILE_NAME)
        {
            FileStream fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
            Encoding r = GetType(fs);
            fs.Close();
            return r;
        }
        private static System.Text.Encoding GetType(FileStream fs)
        {
            byte[] Unicode = new byte[] { 0xFF, 0xFE, 0x41 };
            byte[] UnicodeBIG = new byte[] { 0xFE, 0xFF, 0x00 };
            byte[] UTF8 = new byte[] { 0xEF, 0xBB, 0xBF }; //带BOM 
            Encoding reVal = Encoding.Default;

            BinaryReader r = new BinaryReader(fs, System.Text.Encoding.Default);
            int i;
            int.TryParse(fs.Length.ToString(), out i);
            byte[] ss = r.ReadBytes(i);
            if (IsUTF8Bytes(ss) || (ss[0] == 0xEF && ss[1] == 0xBB && ss[2] == 0xBF))
            {
                reVal = Encoding.UTF8;
            }
            else if (ss[0] == 0xFE && ss[1] == 0xFF && ss[2] == 0x00)
            {
                reVal = Encoding.BigEndianUnicode;
            }
            else if (ss[0] == 0xFF && ss[1] == 0xFE && ss[2] == 0x41)
            {
                reVal = Encoding.Unicode;
            }
            r.Close();
            return reVal;

        }
        private static bool IsUTF8Bytes(byte[] data)
        {
            int charByteCounter = 1; //计算当前正分析的字符应还有的字节数 
            byte curByte; //当前分析的字节. 
            for (int i = 0; i < data.Length; i++)
            {
                curByte = data[i];
                if (charByteCounter == 1)
                {
                    if (curByte >= 0x80)
                    {
                        //判断当前 
                        while (((curByte <<= 1) & 0x80) != 0)
                        {
                            charByteCounter++;
                        }
                        //标记位首位若为非0 则至少以2个1开始 如:110XXXXX...........1111110X 
                        if (charByteCounter == 1 || charByteCounter > 6)
                        {
                            return false;
                        }
                    }
                }
                else
                {
                    //若是UTF-8 此时第一位必须为1 
                    if ((curByte & 0xC0) != 0x80)
                    {
                        return false;
                    }
                    charByteCounter--;
                }
            }
            if (charByteCounter > 1)
            {
                throw new Exception("非预期的byte格式");
            }
            return true;
        }

        public static void SaveLog(int type , string content)
        {
            //这里需要建立一个列表，然后按照列表的内容有无进行文件的写入，防止文件被重复打开。
            Task.Run(()=> {
                StringBuilder sb = new StringBuilder();
                sb.Append("--  typeindex:").Append(type).Append(" time:  ").Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).Append("\n");
                sb.Append(type == 0 ? "" : "-- ").Append(content);
                StringBuilder _fullfilename;
                _fullfilename = new StringBuilder(Application.StartupPath + "\\RecordData\\Log" + DateTime.Now.ToString("yyyy") + "\\");
                if (!Directory.Exists(_fullfilename.ToString())) { Directory.CreateDirectory(_fullfilename.ToString()); }
                _fullfilename.Append(DateTime.Now.ToString("yyyy-MM-dd") + ".log");
                try
                {
                    using (StreamWriter writer = new StreamWriter(_fullfilename.ToString(), true, Encoding.GetEncoding(936)))
                    {
                        writer.WriteLine(sb);
                    }
                }
                catch (Exception ex)
                {
                    _fullfilename = new StringBuilder(Application.StartupPath + "\\RecordData\\errorLog" + DateTime.Now.ToString("yyyy") + "\\");
                    if (!Directory.Exists(_fullfilename.ToString())) { Directory.CreateDirectory(_fullfilename.ToString()); }
                    _fullfilename.Append(DateTime.Now.ToString("yyyy-MM-dd") + ".log");
                    sb.AppendLine(ex.Message);
                    using (StreamWriter writer = new StreamWriter(_fullfilename.ToString(), true, Encoding.GetEncoding(936)))
                    {
                        writer.WriteLine(sb);
                    }
                    //throw;
                }
            });
        }
    }
}
